package ar.com.raulsanchez.syncrolist;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.AdapterContextMenuInfo;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class HomeActivity extends ListActivity {

    private WebServiceInterface webServiceInterface;

    ListView 				lv;
    ActividadAdapter 		actividadAdapter;    
    ArrayList<Actividad>	actividadArray = null;
    //Actividades 		list;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);		
		
		registerForContextMenu(getListView());

		Integer usuario_id = 1;
		//lv = (ListView) findViewById(R.id.lista);
		lv = (ListView) getListView();
		actividadArray = new ArrayList<Actividad>();
		actividadAdapter = new ActividadAdapter(HomeActivity.this,R.layout.item_activity,actividadArray);
		lv.setAdapter(actividadAdapter);
		
		new ActivitiesSync().execute(usuario_id);
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.activity_home, menu);
        return true;
    }
	
	@Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
            case R.id.item_sync:
            	//sincronizarNotas();
                return true;
            case R.id.item_contactos:
                return true;
            case R.id.item_agregar_actividad:
            	return true; 	
            case R.id.item_agregar_contacto:
            	return true; 	
        }

        return super.onMenuItemSelected(featureId, item);
    }
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.activity_home, menu);
    } // onCreateContextMenu
	
	/*public static ArrayList<Actividad> getActivities() {
		return actividadArray;
	}*/
	
    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

        switch(item.getItemId()) {
            case R.id.item_borrar:
                //mDbHelper.borrarNota(info.id,true);
                //cargarLista();
                return true;
            case R.id.item_editar:
            	Intent i = new Intent(this, EditActivity.class);
                //i.putExtra(NotasBdAdaptador.COL_ID, info.id);
                //startActivityForResult(i, ACTIVITY_EDITAR);
            	startActivity(i);
        }
        return super.onContextItemSelected(item);
    }
    
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        Intent i = new Intent(this, EditActivity.class);
		i.putExtra("array_id", position);
        startActivityForResult(i,0);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        //actividadAdapter.notifyDataSetChanged();
    }
    
    @Override
    public void finish() {
    	super.finish();
    	//mDbHelper.close();
    }
    

	
    
    

	
	//------------------------------------
	// SUBCLASE LISTACTIVITIESTASK
	//------------------------------------
	private class ActivitiesSync extends AsyncTask<Integer, Void, String> {

		private final ProgressDialog dialog = new ProgressDialog(
                HomeActivity.this);

        protected void onPreExecute() {
        	this.dialog.setMessage("Obteniendo datos...");
            this.dialog.show();
        }

        protected String doInBackground(Integer... data) {
    		webServiceInterface = new WebServiceInterface();
        	String result = webServiceInterface.listActivities(data[0]); //json
        	/*
        	Actividades list = null;
        	list = new Gson().fromJson(result, Actividades.class);
        	return list;*/
        	
        	
        	return result;
        }

        protected void onPostExecute(String arg) {
        	if (this.dialog.isShowing()) {
        		this.dialog.setMessage("Resultado:"+arg.toString());
        		//this.dialog.dismiss();
	
        		Type collectionType = new TypeToken<ArrayList<Actividad>>(){}.getType();
        		List<Actividad> lst = new Gson().fromJson(arg, collectionType);

        		for(Actividad a : lst)
                {
                    actividadArray.add(a);
                }
        		actividadAdapter.notifyDataSetChanged();
        	}
         }

      } // subclass LoginTask

	
	// MANEJO DE LOS TABS
	private class TabListener<T extends Fragment> implements ActionBar.TabListener {
		private Fragment mFragment;
		private final Activity mActivity;
	    private final String mTag;
	
	    private final Class<T> mClass;

        /**
         * Constructor used each time a new tab is created.
         * 
         * @param activity
         *            The host Activity, used to instantiate the fragment
         * @param tag
         *            The identifier tag for the fragment
         * @param clz
         *            The fragment's Class, used to instantiate the fragment
         */

        public TabListener(Activity activity, String tag, Class<T> clz) {
            mActivity = activity;
            mTag = tag;
            mClass = clz;
        }

        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            // Check if the fragment is already initialized
            if (mFragment == null) {
                // If not, instantiate and add it to the activity
                mFragment = Fragment.instantiate(mActivity, mClass.getName());
                ft.add(android.R.id.content, mFragment, mTag);
            } else {
	                // If it exists, simply attach it in order to show it
                ft.attach(mFragment);
            }
        }
        
        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
            if (mFragment != null) {
                // Detach the fragment, because another one is being attached
                ft.detach(mFragment);
            }
        }

        public void onTabReselected(Tab tab, FragmentTransaction ft) {
            // User selected the already selected tab. Usually do nothing.
        }
	    
	} // subclass TabListener

} // class HomeActivity
